package com.shgsh.platform.controller;

import com.shgsh.attribute.model.WordData;
import com.shgsh.platform.service.WordDataService;
import com.shgsh.platform.util.SectionName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by jessy on 2015/8/8.
 */
@Controller
@RequestMapping("/platform/word")
public class WordDataController {

    Logger log = LoggerFactory.getLogger(WordDataController.class);

    @Autowired
    WordDataService wordDataService;

    @RequestMapping(value = "edit",method = RequestMethod.GET)
    public String edit(String source_id,Model model) throws UnsupportedEncodingException {
        if(!StringUtils.isEmpty(source_id)){
            WordData wordData = wordDataService.get(source_id);
            model.addAttribute("wordData",wordData);
            String sectionName = SectionName.returnName(wordData.getSection());
            model.addAttribute("section",wordData.getSection());
            model.addAttribute("sectionName",new String(sectionName.getBytes("iso-8859-1"),"utf-8"));
        }
            List<String> datas = wordDataService.listAttributes();
            model.addAttribute("datas",datas);
        log.debug("request word form .");
        return "/platform/word/edit";
    }

    @RequestMapping(value = "edit",method = RequestMethod.POST)
    public String edit(WordData wordData){
        if(wordData != null){
            if(StringUtils.isEmpty(wordData.getSource_id())){
                wordDataService.save(wordData);
            }else{
                wordDataService.update(wordData);
            }
        }
        return "redirect:/platform/word/list";
    }

    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model){
        List<WordData> wordDataList = wordDataService.list();
        model.addAttribute("wordDataList",wordDataList);
        return "/platform/word/list";
    }

    @RequestMapping(value = "delete",method = RequestMethod.GET)
    public String delete(@RequestParam(value = "word_id",required = true
    )String word_id){
        wordDataService.delete(word_id);
        return "redirect:/platform/word/list";
    }

}
